package com.fw.service.captcha.impl;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.Locale;

import com.fw.service.captcha.CaptchaService;
import com.octo.captcha.engine.image.gimpy.DefaultGimpyEngine;
import com.octo.captcha.service.CaptchaServiceException;
import com.octo.captcha.service.image.DefaultManageableImageCaptchaService;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

/**
 * Description:
 * 
 * @author AS073
 *
 */
public class CaptchaServiceImpl implements CaptchaService {

    private static DefaultManageableImageCaptchaService instance;

    static {
	instance = new DefaultManageableImageCaptchaService();
	instance.setCaptchaEngine(new DefaultGimpyEngine());
    }

    public byte[] loadCaptcha(String sessionId, Locale locale) {
	byte[] captchaChallengeAsJpeg = null;
	ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
	try {
	    BufferedImage challenge = instance.getImageChallengeForID(sessionId, locale);
	    JPEGImageEncoder jpegEncoder = JPEGCodec.createJPEGEncoder(jpegOutputStream);
	    jpegEncoder.encode(challenge);
	} catch (IllegalArgumentException e) {
	    e.printStackTrace();
	} catch (CaptchaServiceException e) {
	    e.printStackTrace();
	} catch (Exception e) {
	    e.printStackTrace();
	}
	captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
	return captchaChallengeAsJpeg;
    }

    public Boolean validateCaptcha(String sessionId, String captcha) {
	Boolean isResponseCorrect = Boolean.FALSE;
	try {
	    isResponseCorrect = instance.validateResponseForID(sessionId, captcha);
	} catch (CaptchaServiceException e) {
	    e.printStackTrace();
	}
	return isResponseCorrect;
    }

}
